package com.kingsoft.demo.xml.dom4j;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.*;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class CreateXML {

	public void create(){
		
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		ResultSetMetaData rsmd=null;
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		    con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","tiger");
			st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs=st.executeQuery("select * from emp_k");
			rsmd=rs.getMetaData();
		    Document doc=DocumentHelper.createDocument();
			
			Element el_rowdata=doc.addElement("ROOT");
            int j=1;
            while(rs.next())
           {
        	  
        	   Element el_row= el_rowdata.addElement("EMP");
        	   Element el_rownum=el_row.addElement("ROWNUM");
               el_rownum.setText(String.valueOf(j));
               j++;
        	   for(int i=1;i<=rsmd.getColumnCount();i++){
      
		         Element el= el_row.addElement(rsmd.getColumnName(i));
		         
		         
                 if(rs.getString(i)!=null && !"".equals(rs.getString(i)))
		             el.setText(rs.getString(i));
                 else
		        	 el.setText("");
		      
		      }
        	   
          }
	 
			try {
				   Writer w= new FileWriter("src/demo1.xml");
					OutputFormat opf=OutputFormat.createPrettyPrint();
					opf.setEncoding("GBK");   
					
					XMLWriter xw=new XMLWriter(w,opf);		
					xw.write(doc);	
					xw.close();
					
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			
		
				try {
					if(rs!=null)	rs.close();
					if(st!=null)    st.close();
					if(con!=null)   con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		}
		

	}

	public static void main(String[] args) {
	    CreateXML cx=new CreateXML();
	    cx.create();
	}
	
	
}

